package com.rjt.redis.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import com.rjt.redis.model.UserModel;
import com.rjt.redis.service.UserService;
@Service
public class UserServiceImpl implements UserService{
	
	@Autowired
	private StringRedisTemplate redisTemplate;

	@Override
	public String add(String userName, String day) {
		// TODO Auto-generated method stub
		String message="success";
		try {
			redisTemplate.opsForValue().set(userName, "1",Long.parseLong(day),TimeUnit.DAYS);
		} catch (Exception e) {
			// TODO: handle exception
			message="error";
		}
		
		
		return message;
	}

	@Override
	public Long find(String userName) {
		// TODO Auto-generated method stub
		return redisTemplate.getExpire(userName,TimeUnit.HOURS);
	}

	
	@Override
	public String del(String userName) {
		// TODO Auto-generated method stub
	
		 String message="success";
			try {
				 redisTemplate.delete(userName);
			} catch (Exception e) {
				// TODO: handle exception
				message="error";
			}
			
			return message;
	}
	
	@Override
	public List<UserModel> findAll() {
		// TODO Auto-generated method stub
		 Set<String> keys = redisTemplate.keys("*");
		 List<UserModel> users=new ArrayList<>();
		 for (String string : keys) {
			UserModel user=new UserModel();
			user.setUserName(string);
			user.setDay(redisTemplate.getExpire(string,TimeUnit.DAYS));
			user.setHour(redisTemplate.getExpire(string,TimeUnit.HOURS));
			user.setMinute(redisTemplate.getExpire(string,TimeUnit.MINUTES));
			users.add(user);
		}
		return users;
	}
}
